import React, { useEffect, useState } from 'react'
import styles from './index.module.css'
import { useDispatch } from 'react-redux'
import { editcity } from '../../store/CitySlice'
import http from '../../utils/http'
import { useNavigate, useParams } from 'react-router-dom'
import { LocationFill } from 'antd-mobile-icons'
import { IndexBar, Card, List, Tag, NavBar, SearchBar } from 'antd-mobile'
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "2c5bdaf7f3b2df74ca6ca629e620ae10",
};
function Index() {
  const navigate = useNavigate()
  const { type } = useParams()
  const dispatch = useDispatch()
  const [citys, setCitys] = useState([])
  const [hotCitie, setHotCitie] = useState([])
  const [searchs, setSearchs] = useState([])
  const [cityCurr, setCityCurr] = useState('获取中')

  const getCity = async () => {
    const res = await http.get('/api/city')

    console.log(res);

    const { code, data } = res.data

    if (code === 200) {
      setCitys(data.city)
      setHotCitie(data.hotCities)
    }
  }

  const getGeolocity = () => {
    AMapLoader.load({
      key: "d64f5e8da2073a4030ac01811788312d", //申请好的 Web 端开发 Key，首次调用 load 时必填
      version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
    })
      .then((AMap) => {
        AMap.plugin('AMap.CitySearch', function () {
          var searchs = new AMap.CitySearch()
          searchs.getLocalCity(function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // 查询成功，result即为当前所在城市信息
              console.log(result.city);

              setCityCurr(result.city)
            }
          });
        });
      })
      .catch((e) => {
        console.error(e); //加载错误提示
      });
  }

  useEffect(() => {
    getCity()
    getGeolocity()
  }, [])

  const handleSearch = async (val) => {
    if (val === '') {
      setSearchs([])
      return
    }
    const res = await http.get('/api/city/search', { params: { wd: val } })

    console.log(res);

    const { code, data } = res.data

    if (code === 200) {
      setSearchs(data)
    }

  }

  const handleIndex = (city) => {
    dispatch(editcity({ city, type }))
    navigate('/')
  }
  return (
    <div>
      <NavBar onBack={() => navigate(-1)}>城市页</NavBar>
      <SearchBar placeholder='请输入内容' onChange={handleSearch} />
      <div className={styles.search}>
        <div className={styles.search_wroe}>
          {
            searchs?.map((item, ind) => (
              <List.Item key={ind} onClick={() => handleIndex(item.name)}>{item.name}</List.Item>
            ))
          }
        </div>
      </div>
      <Card className={styles.citys_wroe}>
        <span>当前城市:</span>
        <LocationFill />
        <span>{cityCurr}</span>
      </Card>
      <Card title='热门城市'>
        <div className={styles.tags_wroe}>
          {
            hotCitie?.map((item, ind) => (
              <Tag key={ind} onClick={() => handleIndex(item.name)}>{item.name}</Tag>
            ))
          }
        </div>
      </Card>
      <Card title='城市列表'>
        {
          <div style={{ height: window.innerHeight }}>
            <IndexBar>
              {
                citys?.map(group => {
                  const { initial, list } = group
                  return (
                    <IndexBar.Panel
                      index={initial}
                      title={`${initial}`}
                      key={`${initial}`}
                    >
                      <List>
                        {list.map((item, index) => (
                          <List.Item key={index} onClick={() => handleIndex(item.name)}>{item.name}</List.Item>
                        ))}
                      </List>
                    </IndexBar.Panel>
                  )
                })
              }
            </IndexBar>
          </div>
        }
      </Card>
    </div>
  )
}

export default Index
